package com.jzy.gulimall.ware.listener;

import com.jzy.common.to.mq.OrderTo;
import com.jzy.common.to.mq.StockLockTo;
import com.jzy.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author jzy
 * @date 2020/9/22 18:00
 */
@RabbitListener(queues = "stock.release.stock.queue")
@Service
public class StockReleaseListener {

    @Resource
    private WareSkuService wareSkuService;

    /**
     * 库存自动解锁 手动ack
     */
    @RabbitHandler
    public void handlerStockLockedRelease(StockLockTo stockLockTo, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息");
        try {
            wareSkuService.unLockStock(stockLockTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            //消息拒绝以后重新放入队列
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    /**
     * 订单解锁之后发送消息库存,防止库存在订单之前触发解锁
     */
    @RabbitHandler
    public void handlerOrderClose(OrderTo orderTo, Message message, Channel channel) throws IOException {
        System.out.println("收到订单解锁的消息,准备解锁库存");
        try {
            wareSkuService.unLockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            //消息拒绝以后重新放入队列
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
